package com.snailct.bpp.commons.protocol;

import com.snailct.bpp.commons.CommonException;
import com.snailct.bpp.commons.exception.ErrorCode;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

import javax.xml.namespace.QName;

/**
 * WS 调用工具类
 */
public final class WSProtocolHolder {
    private enum ProtocolError{
        @ErrorCode(comment = "Invoker service fail,Unable to sendViaPost to url ${1}service impl!")
        WS_SERVICE_INVOKER_ERROR
    }
    private static WSProtocolHolder instance;
    private WSProtocolHolder(){

    }
    public synchronized static WSProtocolHolder getInstance(){
        if(instance==null){
            instance = new WSProtocolHolder();
        }
        return instance;
    }
    public Object[] request(String serviceAddr,String method,String args,String qname) throws CommonException {
        RPCServiceClient rpcServiceClient = null;
        try {
            rpcServiceClient = new RPCServiceClient();
            Options options = rpcServiceClient.getOptions();
            EndpointReference endpointReference = new EndpointReference(serviceAddr);
            options.setTo(endpointReference);
            QName invokeService = new QName(qname,method);
            Class[] rtnTypes = new Class[]{String.class};
            Object[] params = new Object[]{args};
            Object[] responses = rpcServiceClient.invokeBlocking(invokeService,params,rtnTypes);
            return responses;
        } catch (AxisFault e) {
            throw new CommonException(ProtocolError.WS_SERVICE_INVOKER_ERROR,serviceAddr);
        }

    }
}
